package com.zhia.demo.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhia.demo.dao.UserDao;
import com.zhia.demo.entity.UserEntity;
import com.zhia.demo.service.UserService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @author DONG
 * @create 2023/9/20 21:59
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

    @Override
    public UserEntity getUser(String username, String password) {
        UserEntity user = baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("uname", username));
        BCryptPasswordEncoder bpe = new BCryptPasswordEncoder();
        if (user != null) {
            if (!bpe.matches(password, user.getPwd())) {
                user.setPwd(null);
            }
            return user;
        } else {
            return null;
        }

    }

    @Override
    public boolean checkUser(String uname) {
        long count = baseMapper.selectCount(new QueryWrapper<UserEntity>().eq("uname",uname));
        return count == 0;
    }

    @Override
    public void addUser(UserEntity user) {
        user.setNickname(user.getUname());
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String password = passwordEncoder.encode(user.getPwd());
        user.setPwd(password);
        save(user);
    }
}
